import React, {useEffect, useState} from "react";
import {Text} from "react-native-elements";
import {Dimensions, StyleSheet, TextInput, TouchableHighlight, View} from "react-native";
import {fontSize_15, fontSize_16} from "./theme";
import {getTokenDecimals, getTokenName, getTokenSymbol} from "./smartxL2Libs/smartxL2Web3";
import SimpleToast from "react-native-simple-toast";
import {addTokenToChain, nowWallet, tokenNetType} from "./smartxL2Libs/L2_Data";

const {width,height,scale} = Dimensions.get("window");

const L2_CustomToken = ({navigation,route}:any) => {
    const [tokenInfo,setTokenInfo] = useState([
        {
            title:"代币合约",
            placeHoldText:"请输入代币合约地址",
            content:""
        },
        {
            title:"代币符号",
            placeHoldText:"请输入代币符号",
            content:""
        },
        {
            title:"代币名称",
            placeHoldText:"请输入代币名称",
            content:""
        },
        {
            title:"代币精度",
            placeHoldText:"请输入代币精度",
            content:""
        },
    ])
    useEffect(()=>{
        navigation.setOptions({
            title:"Add token"
        })
    },[])
    const searchTokenInfo = async () => {
        try {
            let tokenAddress = tokenInfo[0].content;
            let symbol = await getTokenSymbol(tokenAddress);
            let decimals = await getTokenDecimals(tokenAddress);
            let name = await getTokenName(tokenAddress);
            let listTemp = [...tokenInfo];
            console.log(symbol)
            console.log(decimals)
            if(symbol.success && decimals.success && name.success)
            {
                listTemp[1].content = symbol.data.symbol.toString();
                listTemp[2].content = name.data.name.toString();
                listTemp[3].content = decimals.data.decimals.toString();
                setTokenInfo(listTemp)
            }
            else
            {
                SimpleToast.show("未查询到token信息，请检查合约是否正确")
            }
        }catch (e) {
                SimpleToast.show("未查询到token信息，请检查合约是否正确")
        }
    }
    return (
        <View style={styles.container}>
            {
                tokenInfo.length?
                    tokenInfo.map((item,index)=>(
                        <View style={styles.tokenInfoContainer} key={"tokenInfo_"+index}>
                            <Text style={styles.tokenInfoTitle}>{item.title}</Text>
                            <TextInput
                                underlineColorAndroid={'transparent'}
                                placeholder= {item.placeHoldText}
                                value={item.content}
                                // multiline={true}
                                onChangeText={
                                    (value) => {
                                        console.log(index)
                                        let temp = item;
                                        temp.content = value.trim();
                                        let listTemp = [...tokenInfo]
                                        listTemp[index] = temp;
                                        listTemp[3].content = "";
                                        setTokenInfo(listTemp)
                                    }
                                }
                                style={{
                                    minHeight:40,
                                    padding:0,
                                    paddingLeft:0,
                                    paddingRight:20,
                                    fontSize:fontSize_15,
                                    lineHeight:20,
                                    borderBottomWidth:2/scale,
                                    borderBottomColor:"#e5e5e5"
                                    // backgroundColor:"pink",
                                }}

                                editable={index !== 3}
                                onEndEditing={()=>{
                                    if(index!==0)
                                    {
                                        return
                                    }
                                    searchTokenInfo()
                                }}
                            />
                        </View>
                    )):null
            }
            <View style={{flex:1}}/>
            <View style={styles.transferContainer}>
                <TouchableHighlight underlayColor={"#f5f6f8"} onPress={()=>{
                    navigation.goBack();
                }}
                                    style={[styles.transferBTN,styles.backgroundFrom,styles.marginRight10]}>
                    <Text style={[styles.transferTitle,{color:"#98999b"}]}>取消</Text>
                </TouchableHighlight>
                <TouchableHighlight underlayColor={"#96c4ff"} onPress={async () => {
                    if (!tokenInfo[3].content) {
                        return;
                    }
                    let token: tokenNetType = {
                        chainID: nowWallet.chainID,
                        tokenSymbloName: tokenInfo[1].content,
                        tokenName: tokenInfo[2].content,
                        tokenAddress: tokenInfo[0].content,
                        tokenPrice_CNY: "0",
                        tokenPrice_USDT: "0",
                        tokenImg: "",
                        balance: "0",
                        walletAddress: nowWallet.address
                    }
                    let res = await addTokenToChain(nowWallet.chainID, token, nowWallet.address)
                    if(!res.success)
                    {
                        SimpleToast.show(res.falseReason)
                        return ;
                    }
                    navigation.navigate("L2_Tabs")
                    SimpleToast.show("添加成功")
                }}
                    style={[styles.transferBTN,tokenInfo[3].content?styles.backgroundToLight:styles.backgroundTo]}>
                    <Text style={styles.transferTitle}>确认</Text>
                </TouchableHighlight>

            </View>
        </View>
    )
}
const styles = StyleSheet.create({
    container: {
        flex: 1,
        width: width,
        alignItems: "center",
        flexDirection: "column",
        paddingLeft: 10,
        // paddingRight: 10,
        backgroundColor: "white",
    },
    tokenInfoContainer:{
      width:"100%",
        paddingTop:20
    },
    tokenInfoTitle:{
        fontSize:fontSize_16,
        lineHeight:25
    },
    transferContainer:{
        height:65,
        width:width,
        padding:10,
        marginLeft:10,
        paddingRight:20,
        flexDirection:"row",
        alignItems:"center",
        justifyContent:"space-between",
    },
    transferBTN:{
        flex:1,
        height:"100%",
        alignItems:"center",
        justifyContent:"center",
        borderRadius:10,
    },
    transferTitle:{
        fontSize:fontSize_15,
        color:"white"
    },
    backgroundFrom:{
        backgroundColor:"#f5f6f8"
    },
    backgroundTo:{
        backgroundColor:"#96c4ff",
    },
    backgroundToLight:{
        backgroundColor:"#1d82fe",
    },
    marginRight10:{
        marginRight:10
    }
})
export default L2_CustomToken;


